/**
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 *
 * @data:2017年10月10日
 * @author:MaShibo
 */
package com.wttech.dzzf.process.util;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.taiji.sdk.model.comm.protocol.AbstractSdtsRequest;
import cn.com.taiji.sdk.tools.ObjectMapperBuilder;
import etc.com.fasterxml.jackson.databind.ObjectMapper;
import etc.com.fasterxml.jackson.databind.introspect.Annotated;
import etc.com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import etc.com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import etc.com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

/**
 * 生成json文件工具类
 *
 * @author MaShibo
 * @date 2017年10月10日
 */
public class GenerateJsonFile {


    private static final String DEFAULT_FILEPATH = "C:\\test1";

    private static final String DEFAULT_SENDER = "61";

    private static final String DEFAULT_CHARSET = "UTF-8";

    private static final ObjectMapper MAPPER;

    private static final Logger LOGGER = LoggerFactory.getLogger(GenerateJsonFile.class);

    static {
        MAPPER = ObjectMapperBuilder.create().build();

    }

    private GenerateJsonFile() {

    }

    @SuppressWarnings("serial")
    public static void generateJsonFile(AbstractSdtsRequest reqObj) {
        MAPPER.setFilterProvider(new SimpleFilterProvider().addFilter(reqObj.getClass().getName(),
                SimpleBeanPropertyFilter.serializeAllExcept("timeMillStr")));
        MAPPER.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {


            @Override
            public Object findFilterId(Annotated a) {
                return a.getName();
            }

        });
        String fileName = reqObj.getFileName(DEFAULT_SENDER);
        String filePath = DEFAULT_FILEPATH + File.separator + fileName;
        outputFile(filePath, reqObj);
    }

    @SuppressWarnings("serial")
    public static <T extends AbstractSdtsRequest> void generateJsonFile(List<T> reqObjs, String storeDirectory) {
        MAPPER.setFilterProvider(new SimpleFilterProvider().addFilter(reqObjs.get(0).getClass().getName(),
                SimpleBeanPropertyFilter.serializeAllExcept("timeMillStr")));
        MAPPER.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {


            @Override
            public Object findFilterId(Annotated a) {
                return a.getName();
            }

        });
        String fileName = reqObjs.get(0).getFileName(DEFAULT_SENDER);
        String directoryPath = DEFAULT_FILEPATH + File.separator + (StringUtils.isBlank(storeDirectory) ? StringUtils.EMPTY : storeDirectory + File.separator);
        String filePath = directoryPath + fileName;
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            if (directory.mkdirs()) {
                outputFile(filePath, reqObjs);
            } else {
                LOGGER.info("目录{}创建失败", directoryPath);
            }
        }
        outputFile(filePath, reqObjs);
    }


    private static void outputFile(String filePath, Object obj) {
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            FileChannel fc = fos.getChannel();
            String json = MAPPER.writeValueAsString(obj);
            ByteBuffer buffer = Charset.forName(DEFAULT_CHARSET).encode(json);
            fc.write(buffer);
            fc.close();
            LOGGER.info("文件{}已生成", filePath);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }

}
